package com.ruoyi.business.goods.service.impl;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.business.base.JoBaseServiceImpl;
import com.ruoyi.business.base.PageParam;
import com.ruoyi.business.goods.domain.JbCommodity;
import com.ruoyi.business.goods.domain.vo.JbCommodityVo;
import com.ruoyi.business.goods.domain.vo.JbProductVO;
import com.ruoyi.business.goods.mapper.JbCommodityMapper;
import com.ruoyi.business.goods.service.JbCommodityService;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.StringJoiner;

/**
 * 商品Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-11
 */
@Service
public class JbCommodityServiceImpl
        extends JoBaseServiceImpl<JbCommodityMapper, JbCommodity>
        implements JbCommodityService
{

    @Override
    public List<JbCommodity> selectCommodityList(List<Long> ids)
    {
        LambdaQueryWrapper<JbCommodity> list = new LambdaQueryWrapper<>();
        list.in(JbCommodity::getId, ids);
        return this.list(list);
    }

    @Override
    public List<JbCommodityVo> listNameAll(JbCommodity jbCommodity)
    {
        StringJoiner sql = new StringJoiner(" ").add("""
                SELECT
                	jc.*,
                	jp.pesticide_registration_number\s
                FROM
                	jb_commodity jc
                	INNER JOIN jb_product jp ON jc.product_id = jp.id\s
                WHERE
                	jc.del_flag = 0\s
                	AND jp.del_flag =0
                """);
        sql.add(joSqlUtil.sqlIf(" and INSTR(jc.commodity_name,'#{commodityName}')>0"
                , jbCommodity.getCommodityName()));
        String s = joSqlUtil.sqlJson(sql.toString(), jbCommodity);
        return joSqlUtil.jsonToEntity(baseMapper.findJson(s), JbCommodityVo.class);
    }

    @Override
    public IPage<JbProductVO> pageCommodityProduct(PageParam pageParam, JbProductVO JbProductVO, JSONObject jsonObject)
    {
        StringJoiner sql = new StringJoiner(" ").add("""
                SELECT
                	jbp.id productId,
                	jbp.active_ingredient_1 activeIngredient1,
                	jbp.active_ingredient_2 activeIngredient2,
                	jbp.active_ingredient_3 activeIngredient3,
                	jbp.recommended_crops recommendedCrops,
                	jbp.recommended_targets recommendedTargets,
                	jbp.dosage_form dosageForm,
                	jbp.brand_name brandName,
                	jbc.commodity_name commodityName,
                	jbc.id commodityId\s
                FROM
                	jb_product jbp right JOIN 
                	jb_commodity jbc ON jbp.id = jbc.product_id\s
                WHERE
                    jbp.del_flag = '0'\s
                    and jbc.del_flag = '0'\s
                """);
        //商品名称
        sql.add(joSqlUtil.sqlIf("AND jbc.commodity_name LIKE '%#{commodityName}%'\s", JbProductVO.getCommodityName()));
        //有效成分1
        sql.add(joSqlUtil.sqlIf("AND jbp.active_ingredient_1 LIKE '%#{activeIngredient1}%'\s",
                JbProductVO.getActiveIngredient1()));
        //有效成分2
        sql.add(joSqlUtil.sqlIf("AND jbp.active_ingredient_2 LIKE '%#{activeIngredient2}%'\s",
                JbProductVO.getActiveIngredient2()));
        //有效成分3
        sql.add(joSqlUtil.sqlIf("AND jbp.active_ingredient_3 LIKE '%#{activeIngredient3}%'\s",
                JbProductVO.getActiveIngredient3()));
        //作物类型
        sql.add(joSqlUtil.sqlIf("AND jbp.recommended_crops LIKE '%#{recommendedCrops}%'\s",
                JbProductVO.getRecommendedCrops()));
        //靶标
        sql.add(joSqlUtil.sqlIf("AND jbp.recommended_targets LIKE '%#{recommendedTargets}%'\s",
                JbProductVO.getRecommendedTargets()));
        //剂型
        sql.add(joSqlUtil.sqlIf("AND jbp.dosage_form LIKE '%#{dosageForm}%'\s",
                JbProductVO.getDosageForm()));
        //商品品牌
        sql.add(joSqlUtil.sqlIf("AND jbp.brand_name LIKE '%#{brandName}%'\s",
                JbProductVO.getBrandName()));
        //是否启用
        sql.add("AND jbc.status = '0'\s");
        //商品渠道
        sql.add(StringUtils.format("AND jbc.channel_type like '%{}%'\s", jsonObject.getString("channel")));

        String channel = jsonObject.getString("channel");
        String ids = jsonObject.getString("ids");

        if ("1002".equals(channel) && StrUtil.isNotEmpty(ids))
        {
            String id1 = """
                    (
                        jbc.id in (select 
                                commodity_id 
                            from 
                                jb_commodity_offline_price jcop 
                            where 
                                jcop.department_ids ='0'
                            )
                    )
                    """;
            String id2 = """
                    (
                        jbc.id in (select 
                                commodity_id 
                            from 
                                jb_commodity_offline_price jcop 
                            where 
                            	jcop.department_ids IS NOT NULL 
                                AND jcop.department_ids <> '' 
                                AND jcop.department_ids <> '0' 
                                AND jcop.department_ids REGEXP '{}' 
                            )
                    )
                    """;
            id2 = StringUtils.format(id2, ids.replaceAll(",", "|"));
            sql.add(StringUtils.format("({} or {})", id1, id2));
        }

        String s = joSqlUtil.sqlJson(sql.toString(), JbProductVO);
        return joSqlUtil.jsonToEntity(baseMapper.pageJson(pageParam.b(), s), JbProductVO.class);
    }

    @Override
    public IPage<JbProductVO> findInventory(PageParam pageParam, JbProductVO JbProductVO)
    {
        StringJoiner sql = new StringJoiner(" ").add("""
                SELECT
                    jbp.id productId,
                    jbc.id commodityId,
                    jbc.commodity_name commodityName,
                    jbc.main_image_url mainImageUrl,
                    jbp.product_name,
                    jbc.min_unit,
                    jbc.case_quantity,
                    jbp.sales_channel,
                    tci.inventory,
                    tci.update_time\s
                FROM
                    jb_product jbp
                    LEFT JOIN jb_commodity jbc ON jbp.id = jbc.product_id
                    LEFT JOIN jb_product_recipe tci ON jbc.id = tci.commodity_id\s
                WHERE
                    jbp.del_flag = '0'\s
                """);
        sql.add(joSqlUtil.sqlIf("AND jbp.classify_id = #{classifyId}\s", JbProductVO.getClassifyId()));
        sql.add(joSqlUtil.sqlIf("AND jbp.sales_channel = '#{salesChannel}'\s", JbProductVO.getSalesChannel()));
        sql.add(joSqlUtil.sqlIf("AND jbc.commodity_name LIKE '%#{commodityName}%'\s",
                JbProductVO.getCommodityName()));

        String s = joSqlUtil.sqlJson(sql.toString(), JbProductVO);
        return joSqlUtil.jsonToEntity(baseMapper.pageAndCountJson(pageParam.b(), s), JbProductVO.class);
    }

}
